<?php

App::uses('AppController', 'Controller');

/**
 * Sales Controller
 *
 * @property Sale $Sale
 */
class SalesController extends AppController {

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        if ((!isset($this->request->data['from']) && !isset($this->request->data['to'])) ||
                (empty($this->request->data['from']) && empty($this->request->data['to']))) {
            $this->Sale->recursive = 1;
            $this->paginate = array('order' => 'Sale.date DESC');
            $this->set('sales', $this->paginate());
        } else {

            $from = $this->request->data('from');
            $to = $this->request->data('to');

            $this->set(compact('from', 'to'));

            $fechaInicio = date("Y-m-d", strtotime(trim($this->request->data('from'))));
            $fechaInicio .=' 00:00:00';
            if (empty($this->request->data['to'])) {
                $fechaFin = date("Y-m-d", strtotime(trim($this->request->data('from'))));
            } else {
                $fechaFin = date("Y-m-d", strtotime(trim($this->request->data('to'))));
            }
            $fechaFin .= ' 24:00:00';

            $this->paginate = array('limit' => 10, 'order' => 'Sale.date DESC');
            $this->set('sales', $this->paginate(array('AND' => array('Sale.date >=' => $fechaInicio,
                            'Sale.date <=' => $fechaFin))
                    ));
        }
    }

    public function export($from = null, $to = null) {
        $this->Sale->recursive = 1;


        App::uses('Folder', 'Utility');
        App::uses('File', 'Utility');

        $name = 'ventas_' . date('dmY') . '.csv';
        $csv_file = 'files/ventas/' . $name;
        $csv = "";

        if ((!isset($from) && !isset($to)) ||
                (empty($from) && empty($to))) {

            $contacts = $this->Sale->find('all', array('order' => 'Sale.date DESC'));
        } else {


            $fechaInicio = date("Y-m-d", strtotime(trim($from)));
            $fechaInicio .=' 00:00:00';

            if (empty($to)) {

                $fechaFin = date("Y-m-d", strtotime(trim($from)));
            } else {

                $fechaFin = date("Y-m-d", strtotime(trim($to)));
            }

            $fechaFin .= ' 24:00:00';

            $contacts = $this->Sale->find('all', array(
                'conditions' => array(
                    'AND' => array('Sale.date >=' => $fechaInicio, 'Sale.date <=' => $fechaFin)
                ), array('Sale' => 'Sale.date desc')
                    ));
        }


        $csv .= "Resumen de Productos Comprados\n";
        $csv .= "Vendedor; Punto de Venta; Fecha; Nro de Ticket; Total Parcial($)\n";
        $total_general = 0;


        foreach ($contacts as $key => $contact) {
            $csv .= "{$contact['User']['name']};";
            $csv .= "{$contact['Shop']['name']};";

            $datetime = date('d/m/Y H:i:s', strtotime($contact['Sale']['date']));
            $csv .= "{$datetime};";

            $csv .= "{$contact['Sale']['ticket_number']}\n";

////      Calculo total parcial y acumulo para total final
//      $total_parcial = $contact['Sale']['quantity'] * $contact['Sale']['purchase_price'];
//      $total_general += $total_parcial;
//
//      $csv .= "{$total_parcial}\n";
        }


        //Generamos el csv de todos los datos
        $file = new File($csv_file, true, 0777);
        $file->create();
//    if (!$file->open("w")) {
//      $this->Session->setFlash(__('No se puede abrir el archivo'));
//      $this->redirect(array('action' => 'index'));
//    }
        if (!$file->write(utf8_decode($csv))) {
            $this->Session->setFlash(__('No se puede escribir en el archivo'));
            $this->redirect(array('action' => 'index'));
        }
        $file->close();

        chmod('files/ventas/' . $name, 0777);
        $this->redirect('/files/ventas/' . $name);
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->Sale->exists($id)) {
            throw new NotFoundException(__('Invalid sale'));
        }
        $options = array('conditions' => array('Sale.' . $this->Sale->primaryKey => $id));
        $this->set('sale', $this->Sale->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function venta() {
        if ($this->request->is('post')) {
            $this->Sale->create();
            if ($this->Sale->save($this->request->data)) {
                $this->Session->setFlash(__('La venta ha sido registrada exitosamente'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La venta No ha sido registrada'));
            }
        }
        $users = $this->Sale->User->find('list');
        $shops = $this->Sale->Shop->find('list');
        $path = func_get_args();

        $this->loadModel('Promotion');
        $promotions = $this->Promotion->find('all');
        $this->set(compact('users', 'shops', 'promotions', 'path'));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->Sale->create();
            if ($this->Sale->save($this->request->data)) {
//                $this->Session->setFlash(__('La venta ha sido registrada exitosamente'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La venta NO ha sido registrada'));
            }
        }
        $users = $this->Sale->User->find('list');
        $shops = $this->Sale->Shop->find('list');
        $this->set(compact('users', 'shops'));
    }

    public function load() {
        
    }

    public function addAjax() {


        if ($this->request->is('post')) {
            $this->Sale->create();

//          Guardo Venta, Linea de Venta e incremento ticket
            if ($this->Sale->save($this->request->data) && $this->addLineSales($this->Sale->getId(), $this->request->data('promotions'), $this->request->data('cashId'))
                    && $this->requestAction('/Tickets/increment/' . $this->request->data('ticket_number'))) {

//                $this->Session->setFlash(__('La venta ha sido registrada exitosamente'));

                $this->redirect(array('action' => 'index'));

                return('Llego');
            } else {
                $this->Session->setFlash(__('Error, Venta no registrada'));
            }
        }

        return('No entro');
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        if (!$this->Sale->exists($id)) {
            throw new NotFoundException(__('Invalid sale'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->Sale->save($this->request->data)) {
                $this->Session->setFlash(__('La venta ha sido guardada exitosamente'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('La venta NO ha sido guardado'));
            }
        } else {
            $options = array('conditions' => array('Sale.' . $this->Sale->primaryKey => $id));
            $this->request->data = $this->Sale->find('first', $options);
        }
        $users = $this->Sale->User->find('list');
        $shops = $this->Sale->Shop->find('list');
        $this->set(compact('users', 'shops'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
//        Si hacemos delete on cascade no repone el stock
//        por cada linea de venta, llamar a delete lines
        $this->deleteLines($id);

//        $this->requestAction('/LineSales/delete/30/1/1/5');


        $this->Sale->id = $id;
        if (!$this->Sale->exists()) {
            throw new NotFoundException(__('Invalid sale'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Sale->delete()) {
            $this->Session->setFlash(__('Venta borrada exitosamente'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Venta No borrada'));
        $this->redirect(array('action' => 'index'));
    }

    public function deleteLines($sale_id = null) {

        $sale = $this->Sale->find('first', array('fields' => array(
                'Sale.shop_id'), 'conditions' => array(
                'Sale.id' => $sale_id
                )));

        $shop_id = $sale['Sale']['shop_id'];

        $this->loadModel('LineSale');
        $options = array('conditions' => array('LineSale.sale_id' => $sale_id));
        $lineSales = $this->LineSale->find('all', $options);

        foreach ($lineSales as $lineSale) {

            $this->requestAction("/LineSales/deleteLine/" . $lineSale['LineSale']['id'] . "/" . $lineSale["LineSale"]["promotion_id"] . "/" . $lineSale["LineSale"]["quantity"] . "/" . $shop_id);
        }

        return true;
    }

    //    Registramos cada linea de la factura

    public function addLineSales($sale_id = null, $description = null, $cashId = null) {

        $arrayDescriptions = explode('/', $description);

        foreach ($arrayDescriptions as $key => $value) {
            $line = explode(':', $value);

            $promotion_id = (int) trim($line[0]);
            $quantity = (int) trim($line[1]);
            $total_line = (float) trim($line[2]);

            $data = array(
                'LineSale' => array('sale_id' => $sale_id, 'promotion_id' => $promotion_id,
                    'quantity' => $quantity, 'total_line' => $total_line,
                    'cash_dailies_id' => $cashId
                )
            );
            $this->loadModel('LineSale');
            $this->LineSale->create();
            if ($this->LineSale->save($data)) {
                $this->discountsProducts($promotion_id, $quantity);
            }
        }

        return true;
    }

    //    Buscamos los N productos de cada promocion y cantidad a utilizar en
    //    por cada a Promo, esa cantidad se descuenta del stock del
    //    Punto de Venta correspondiente

    public function discountsProducts($promotion_id = null, $quantityPromo = null) {

        $shop_id = $this->Session->read('Auth.User.shop_id');

//      listado de productos y cantidad
        $this->loadModel('ProductPromotion');
        $products = $this->ProductPromotion->find('all', array(
            'fields' => array('ProductPromotion.product_id', 'ProductPromotion.quantity'),
            'conditions' => array(
//                'ProductPromotion.shop_id' => $shop_id,
                'ProductPromotion.promotion_id' => $promotion_id))
        );


        foreach ($products as $product) {

            $idProduct = $product['ProductPromotion']['product_id'];
            $quantity = $product['ProductPromotion']['quantity'];

//        con el listado verifico stock y descuento en el Punto de Venta correspondiente
            $this->loadModel('ProductShop');
            $productShop = $this->ProductShop->find('first', array('fields' => array(
                    'ProductShop.current_stock', 'ProductShop.id',), 'conditions' => array(
                    'ProductShop.product_id' => $idProduct,
                    'ProductShop.shop_id' => $shop_id,
                    )));

            $this->ProductShop->id = $productShop['ProductShop']['id'];

            $update_stock = ($productShop['ProductShop']['current_stock'] - ($quantity * $quantityPromo ));
            $this->ProductShop->saveField('current_stock', $update_stock);
        }
    }

    public function bck() {
        $host = 'localhost';
        $user = 'cacho';
        $pass = 'a123456.';
        $name = 'villa_dispacher';
        $tables = '*';

        $link = mysql_connect($host, $user, $pass);

// Controlamos el error de conexion  
        if (!$link) {
            die('No puedo conectar, error : ' . mysql_error());
        }

        mysql_select_db($name, $link);

// Seleccionamos la BD   

        $return = "";

        //get all of the tables
        if ($tables == '*') {
            $tables = array();
            $result = mysql_query('SHOW TABLES');
            while ($row = mysql_fetch_row($result)) {
                $tables[] = $row[0];
            }
        } else {
            $tables = is_array($tables) ? $tables : explode(',', $tables);
        }

        //cycle through
        foreach ($tables as $table) {
            $result = mysql_query('SELECT * FROM ' . $table);
            $num_fields = mysql_num_fields($result);

            $return.= 'DROP TABLE ' . $table . ';';
            $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE ' . $table));
            $return.= "\n\n" . $row2[1] . ";\n\n";

            for ($i = 0; $i < $num_fields; $i++) {
                while ($row = mysql_fetch_row($result)) {
                    $return.= 'INSERT INTO ' . $table . ' VALUES(';
                    for ($j = 0; $j < $num_fields; $j++) {
                        $row[$j] = addslashes($row[$j]);
                        $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
                        if (isset($row[$j])) {
                            $return.= '"' . $row[$j] . '"';
                        } else {
                            $return.= '""';
                        }
                        if ($j < ($num_fields - 1)) {
                            $return.= ',';
                        }
                    }
                    $return.= ");\n";
                }
            }
            $return.="\n\n\n";
        }

        // Generate the filename for the sql file
        $file = 'files/bck/dbbackup_' . date("d.m.Y_H:i:s") . '.sql';


        // Save the sql file
        $handle = fopen($file, 'w+');
        fwrite($handle, $return);
        fclose($handle);

        chmod($file, 0777);
        // Close MySQL Connection
        mysql_close();
    }

}
